package com.repro.lib.imageload.utils

import android.graphics.drawable.Drawable
import com.bumptech.glide.integration.webp.decoder.WebpDrawable
import java.lang.reflect.InvocationTargetException
import com.bumptech.glide.load.engine.GlideException

import com.bumptech.glide.request.RequestListener

import android.R

import com.bumptech.glide.Glide

import com.bumptech.glide.integration.webp.decoder.WebpDrawableTransformation

import com.bumptech.glide.load.resource.bitmap.CircleCrop

import android.graphics.Bitmap
import android.widget.ImageView
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.Transformation


object WebpUtils {

    /**
     * 获取webp的播放时间
     */
    @JvmStatic
    private fun getWebpPlayTime(resource: Drawable): Int {
        val webpDrawable = resource as WebpDrawable;
        try {
            val gifStateField = WebpDrawable::class.java.getDeclaredField("state");
            gifStateField.isAccessible = true
            val gifStateClass =
                Class.forName("com.bumptech.glide.integration.webp.decoder.WebpDrawable\$WebpState");
            val gifFrameLoaderField = gifStateClass.getDeclaredField("frameLoader");
            gifFrameLoaderField.isAccessible = true

            val gifFrameLoaderClass =
                Class.forName("com.bumptech.glide.integration.webp.decoder.WebpFrameLoader");
            val gifDecoderField = gifFrameLoaderClass.getDeclaredField("gifDecoder");
            gifDecoderField.isAccessible = true;

            val gifDecoderClass = Class.forName("com.bumptech.glide.gifdecoder.GifDecoder")
            val gifDecoder = gifDecoderField.get(
                gifFrameLoaderField.get(
                    gifStateField.get(
                        resource
                    )
                )
            )
            val getDelayMethod = gifDecoderClass.getDeclaredMethod("getDelay", Int::class.java)
            getDelayMethod.isAccessible = true;
            // 设置只播放一次
            // 获得总帧数
            val count = webpDrawable.frameCount
            var delay = 0
            for (index in 1..count) {
                delay += getDelayMethod.invoke(gifDecoder, index) as Int
            }
            return delay;
        } catch (e: NoSuchFieldException) {
            e.printStackTrace();
        } catch (e: ClassNotFoundException) {
            e.printStackTrace();
        } catch (e: IllegalAccessException) {
            e.printStackTrace();
        } catch (e: NoSuchMethodException) {
            e.printStackTrace();
        } catch (e: InvocationTargetException) {
            e.printStackTrace();
        }
        return 0;
    }

    @JvmStatic
    fun webpPlayAndCount(
        imageView: ImageView,
        url: String,
        count: Int,
        mDelay: (delay: Int) -> Unit
    ) {
        val circleCrop: Transformation<Bitmap> = CircleCrop()
        val webpDrawableTransformation = WebpDrawableTransformation(circleCrop)
        Glide.with(imageView.context).load(url)
            .addListener(object : RequestListener<Drawable?> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: com.bumptech.glide.request.target.Target<Drawable?>?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable?,
                    model: Any?,
                    target: com.bumptech.glide.request.target.Target<Drawable?>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    setLoopCount(resource as WebpDrawable, count)
                    val delay = getWebpPlayTime(resource)
                    mDelay(delay)
                    return false
                }

            }).optionalTransform(circleCrop)
            .optionalTransform(WebpDrawable::class.java, webpDrawableTransformation)
            .skipMemoryCache(true)
            .into(imageView)
    }

    @JvmStatic
    private fun setLoopCount(resource: WebpDrawable, count: Int = 1) {
        resource.loopCount = count
    }
}